<?php 
namespace app\admin\controller;

use think\Request;
use think\Exception;
use app\common\model\Article as ArticleModel;
use app\common\controller\Upload;
use app\common\controller\Richtext;
use app\common\model\Badge;

class Article extends Base
{
	/**
	 * 文章列表
	 * @param Request $request
	 * @return unknown
	 */
	public function index(Request $request)
	{
		$list = ArticleModel::where([['state','>',0]])->order('state desc,id desc')->paginate();
		$list = $list->toArray();
		foreach ($list['data'] as &$rows) {
			$rows['content'] = Richtext::getStirng($rows['content'],40).'...';
		}
		if($request->isAjax()){
			return $this->success($list);
		}
		$this->assign('list',json_encode($list));
		return view();
	}
	
	/**
	 * 添加文章
	 * @param Request $request
	 * @throws Exception
	 * @return unknown
	 */
	public function addArticle(Request $request)
	{
		if ($request->isAjax()) {
			$data = $request -> post('');
			try {
				if(!$data['title'])throw new Exception('标题不能为空');
				if(!$data['cover'])throw new Exception('封面不能为空');
				if(!$data['content'])throw new Exception('内容不能为空');
				$data['cover'] = Upload::base64($data['cover'],config('path.cover'));
				$data['create_time'] = time();
				$data['update_time'] = time();
				ArticleModel::create($data);
			} catch (Exception $e) {
				return $this->error($e->getMessage());
			}
			return $this->success('发布成功');
		}
		//获取标签列表
		$badge = Badge::where(['state' => 1])->select()->toArray();
		$this->assign('badge',json_encode($badge));
		return view();
	}
}